Controller's @ExceptionHandler Method only catches Exceptions thrown inside the same Controller.
Use @ControllerAdvice class as a central place to catch Exceptions from all Controllers.
Exception Methods (differ base on the type of Exception)
MyController.java (example for Request Parameters)
@Controller
public class MyController {
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public String handleExceptions(MissingServletRequestParameterException exception) {
//GET EXCEPTION DETAILS
String parameterType = exception.getParameterType(); //String
String parameterName = exception.getParameterName(); //name
String message = exception.getMessage(); //Required String parameter 'name' is not present
//RETURN MESSAGE
return message;
}
MyController.java
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public String handleIdentifiersNotMatchingException(MissingServletRequestParameterException exception) {
//GET EXCEPTION DETAILS
String parameterType = exception.getParameterType(); //String
String parameterName = exception.getParameterName(); //name
String message = exception.getMessage(); //Required String parameter 'name' is not present
//RETURN MESSAGE
return message;
}
}